package io.gitee.thinkbungee.dao.impl;

import io.gitee.thinkbungee.adaptor.MongoTableInfoAdaptor;
import io.gitee.thinkbungee.config.MongoCondition;
import io.gitee.thinkbungee.dao.GeneratorDao;
import io.gitee.thinkbungee.entity.mongo.MongoDefinition;
import io.gitee.thinkbungee.factory.MongoDBCollectionFactory;
import io.gitee.thinkbungee.utils.mongo.MongoManager;
import io.gitee.thinkbungee.utils.mongo.MongoScanner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * mongo实现
 *
 * @author chenyichang
 * @date 2022/3/8
 */
@Repository
@Conditional(MongoCondition.class)
public class MongoDBGeneratorDao implements GeneratorDao {

    @Autowired
    private MongoDBCollectionFactory mongoDBCollectionFactory;

    @Override
    public List<Map<String, Object>> queryList(Map<String, Object> map) {
        List<String> collectionNames = MongoDBCollectionFactory.getCollectionNames(map);
        return (List) MongoTableInfoAdaptor.tableInfo(collectionNames);
    }

    /**
     * mongo集合可随意创建
     *
     * @param tableName 数据库名
     * @return
     */
    @Override
    public Map<String, String> queryTable(String tableName) {
        Map<String, String> result = new HashMap<>();
        result.put("engine", "");
        result.put("createTime", "");
        result.put("tableComment", "");
        result.put("tableName", tableName);
        return result;
    }

    @Override
    public List<Map<String, String>> queryColumns(String tableName) {
        MongoDefinition mongoDefinition = MongoManager.getInfo(tableName);
        if (mongoDefinition == null) {
            MongoScanner mongoScanner = new MongoScanner(mongoDBCollectionFactory.getCollection(tableName));
            mongoDefinition = mongoScanner.getProduct();
        }
        return MongoTableInfoAdaptor.columnInfo(mongoDefinition);
    }

}
